package chapter13;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Properties;

/**
 * 使用PreparedStatement进行插入
 */
public class PreparedStatementTest {
    private String driver;
    private String url;
    private String username;
    private String password;

    public void initParam(String paramFile) throws Exception {
        Properties props = new Properties();
        props.load(new FileInputStream(paramFile));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        username = props.getProperty("username");
        password = props.getProperty("password");
        Class.forName(driver);
    }

    public void insertUseStatement() throws Exception {
        long start = System.currentTimeMillis();
        try(Connection con = DriverManager.getConnection(url, username, password);
            Statement statement = con.createStatement())
        {
            for (int i = 0; i < 100; i++) {
                //String sql = "insert into t_student values(null, '姓名"+i+"', 1)";
                statement.executeUpdate("insert into t_student values(null, '姓名"+i+"', 1)");
            }
            System.out.println("使用Statement耗时:" + (System.currentTimeMillis() - start));
        }
    }

    public void insertUsePrepared() throws Exception {
        long start = System.currentTimeMillis();
        try(Connection con = DriverManager.getConnection(url, username, password);
            PreparedStatement preparedStatement = con.prepareStatement(
                    "insert into t_student values(null, ?, 1)"
            ))
        {
            for (int i = 0; i < 100; i++) {
                preparedStatement.setString(1, "姓名" + i);
                preparedStatement.executeUpdate();
            }
            System.out.println("使用PreparedStatement耗时:" + (System.currentTimeMillis() - start));
        }
    }

    public static void main(String[] args) throws Exception {
        PreparedStatementTest pst = new PreparedStatementTest();
        pst.initParam("src/main/resources/db.properties");
        pst.insertUseStatement();
        pst.insertUsePrepared();
    }
}
